import { EventEmitter } from 'events'

// 数字人通话状态
export enum DigitalHumanCallState {
  None = 'None',
  Connecting = 'Connecting',
  Connected = 'Connected',
  Error = 'Error'
}

// 数字人智能体类型
export enum DigitalHumanAgentType {
  AvatarAgent = 'AvatarAgent',
  VideoAgent = 'VideoAgent',
  VisionAgent = 'VisionAgent',
  VoiceAgent = 'VoiceAgent'
}

// 数字人配置接口
export interface DigitalHumanConfig {
  agentType: string
  agentId?: string
  region?: string
  userData?: string
  templateConfig?: any
  agentConfig?: any
  sessionId?: string
}

// 数字人引擎配置
export interface DigitalHumanEngineConfig {
  agentElement?: HTMLVideoElement
  rtcEngineConfig?: {
    environment?: 'PRE' | 'PROD'
    useAudioPlugin?: boolean
    dumpAudioData?: boolean
  }
}

// 数字人实例信息
export interface DigitalHumanAgentInfo {
  agentType: string
  instanceId: string
  channelId: string
  userId: string
  rtcToken: string
  reqId: string
}

/**
 * 数字人控制器
 * 基于阿里云智能体SDK实现数字人通话功能
 */
export class DigitalHumanController extends EventEmitter {
  private userId: string
  private userToken: string
  private config: DigitalHumanConfig
  private engineConfig: DigitalHumanEngineConfig
  private state: DigitalHumanCallState = DigitalHumanCallState.None
  private errorMessage: string = ''
  private agentInfo: DigitalHumanAgentInfo | null = null
  private engine: any = null // 阿里云智能体引擎实例

  constructor(userId: string, userToken: string, config: DigitalHumanConfig, engineConfig?: DigitalHumanEngineConfig) {
    super()
    this.userId = userId
    this.userToken = userToken
    this.config = {
      region: 'cn-shanghai',
      agentType: DigitalHumanAgentType.AvatarAgent,
      ...config
    }
    this.engineConfig = engineConfig || {}
  }

  /**
   * 启动数字人通话
   */
  async start(): Promise<void> {
    try {
      this.setState(DigitalHumanCallState.Connecting)

      // 检查浏览器支持
      const isSupported = await this.checkBrowserSupport()
      if (!isSupported) {
        throw new Error('当前浏览器不支持数字人通话功能')
      }

      // 生成数字人实例
      this.agentInfo = await this.generateDigitalHumanAgent()

      // 初始化引擎
      await this.initializeEngine()

      // 开始通话
      await this.startCall()

      this.setState(DigitalHumanCallState.Connected)
      this.emit('callBegin', Date.now())

    } catch (error) {
      console.error('Start digital human call error:', error)
      this.errorMessage = error instanceof Error ? error.message : '启动数字人通话失败'
      this.setState(DigitalHumanCallState.Error)
      throw error
    }
  }

  /**
   * 停止数字人通话
   */
  async stop(): Promise<void> {
    try {
      if (this.engine) {
        await this.engine.handup()
      }
      this.setState(DigitalHumanCallState.None)
      this.emit('callEnd')
    } catch (error) {
      console.error('Stop digital human call error:', error)
      throw error
    }
  }

  /**
   * 销毁控制器
   */
  destroy(): void {
    if (this.engine) {
      this.engine.destroy()
      this.engine = null
    }
    this.removeAllListeners()
  }

  /**
   * 设置数字人视频元素
   */
  setAgentView(videoElement: HTMLVideoElement): void {
    if (this.engine) {
      this.engine.setAgentView(videoElement)
    }
  }

  /**
   * 静音/取消静音麦克风
   */
  muteMicrophone(muted: boolean): void {
    if (this.engine) {
      this.engine.muteLocalMicrophone(muted)
    }
  }

  /**
   * 打断数字人说话
   */
  interruptSpeaking(): void {
    if (this.engine) {
      this.engine.interruptSpeaking()
    }
  }

  /**
   * 发送文本消息给数字人
   */
  sendTextToAgent(text: string): boolean {
    if (this.engine && this.state === DigitalHumanCallState.Connected) {
      return this.engine.sendTextToAgent({ text })
    }
    return false
  }

  /**
   * 获取当前状态
   */
  getState(): DigitalHumanCallState {
    return this.state
  }

  /**
   * 获取错误信息
   */
  getErrorMessage(): string {
    return this.errorMessage
  }

  /**
   * 设置状态
   */
  private setState(newState: DigitalHumanCallState): void {
    if (this.state !== newState) {
      this.state = newState
      this.emit('stateChanged', newState)
    }
  }

  /**
   * 检查浏览器支持
   */
  private async checkBrowserSupport(): Promise<boolean> {
    // 检查WebRTC支持
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      return false
    }

    // 检查其他必要的API
    if (!window.RTCPeerConnection) {
      return false
    }

    return true
  }

  /**
   * 生成数字人智能体实例
   */
  private async generateDigitalHumanAgent(): Promise<DigitalHumanAgentInfo> {
    const response = await fetch('http://localhost:8082/api/v2/digital-human/generateAIAgentCall', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': this.userToken
      },
      body: JSON.stringify({
        user_id: this.userId,
        ai_agent_id: this.config.agentId,
        region: this.config.region,
        workflow_type: this.config.agentType,
        user_data: this.config.userData,
        template_config: this.config.templateConfig ? JSON.stringify(this.config.templateConfig) : undefined,
        agent_config: this.config.agentConfig ? JSON.stringify(this.config.agentConfig) : undefined,
        session_id: this.config.sessionId,
        expire: 24 * 60 * 60 // 24小时
      })
    })

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    const data = await response.json()

    if (data.code !== 200) {
      throw new Error(data.message || '生成数字人实例失败')
    }

    return {
      agentType: this.config.agentType,
      instanceId: data.data.ai_agent_instance_id,
      channelId: data.data.channel_id,
      userId: data.data.ai_agent_user_id,
      rtcToken: data.data.rtc_auth_token,
      reqId: data.data.request_id
    }
  }

  /**
   * 初始化引擎
   */
  private async initializeEngine(): Promise<void> {
    // 这里应该初始化阿里云智能体引擎
    // 由于没有实际的SDK，这里使用模拟实现
    this.engine = {
      setAgentView: (element: HTMLVideoElement) => {
        console.log('Set agent view:', element)
      },

      muteLocalMicrophone: (muted: boolean) => {
        console.log('Mute microphone:', muted)
      },
      interruptSpeaking: () => {
        console.log('Interrupt speaking')
      },
      sendTextToAgent: (request: any) => {
        console.log('Send text to agent:', request)
        return true
      },
      handup: async () => {
        console.log('Handup call')
      },
      destroy: () => {
        console.log('Destroy engine')
      }
    }

    // 设置引擎事件监听
    this.setupEngineEvents()
  }

  /**
   * 设置引擎事件监听
   */
  private setupEngineEvents(): void {
    // 模拟事件监听
    setTimeout(() => {
      this.emit('agentStateChanged', 'Ready')
    }, 1000)

    // 模拟字幕事件
    setInterval(() => {
      if (this.state === DigitalHumanCallState.Connected) {
        this.emit('subtitleReceived', {
          text: '这是模拟的数字人字幕内容',
          timestamp: Date.now(),
          source: 'agent'
        })
      }
    }, 5000)
  }

  /**
   * 开始通话
   */
  private async startCall(): Promise<void> {
    if (!this.agentInfo) {
      throw new Error('数字人实例信息不存在')
    }

    // 这里应该调用引擎的call方法
    console.log('Starting call with agent info:', this.agentInfo)

    // 模拟连接延迟
    await new Promise(resolve => setTimeout(resolve, 2000))
  }
}
